const util = {
    randomNumber() {
        // 生成 最小值 到 最大值 区间的随机数
        const random = (min, max) => {
            return Math.floor(Math.random() * (max - min + 1) + min)
        };
        if (arguments.length === 1) {
            let [length] = arguments;
            // 生成指定长度的随机数字，首位一定不是 0
            let nums = [...Array(length).keys()].map((i) => (i > 0 ? random(0, 9) : random(1, 9)));
            return parseInt(nums.join(''))
        } else if (arguments.length >= 2) {
            let [min, max] = arguments;
            return random(min, max);
        } else {
            return Number.NaN
        }
    },
    randomString(length, chats) {
        if (!length) length = 1;
        if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm';
        let str = '';
        for (let i = 0; i < length; i++) {
            let num = this.randomNumber(0, chats.length - 1);
            str += chats[num]
        }
        return str
    },
    randomUUID() {
        let chats = '0123456789abcdef';
        return this.randomString(32, chats)
    }
};
export default util;

export function postAjax(reqConf) {
    let defaultConf = {
        contentType: "application/json",
        type: "post"
    };
    let conf = Object.assign({}, defaultConf, reqConf);
    if (typeof conf["data"] !== "string") {
        conf["data"] = JSON.stringify(conf["data"]);
    }
    return $.ajax(conf);
}

export function getAjax(reqConf) {
    return $.ajax(reqConf);
}

export function isMobile() {
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    return flag;
}

export function dateFormate(i, g) {
    var h, e;
    var c = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var b = /\\?(.?)/gi;
    var a = function (f, k) {
        return e[f] ? e[f]() : k
    };
    var d = function (k, f) {
        k = String(k);
        while (k.length < f) {
            k = "0" + k
        }
        return k
    };
    e = {
        d: function () {
            return d(e.j(), 2)
        }, D: function () {
            return e.l().slice(0, 3)
        }, j: function () {
            return h.getDate()
        }, l: function () {
            return c[e.w()] + "day"
        }, N: function () {
            return e.w() || 7
        }, S: function () {
            var f = e.j();
            var k = f % 10;
            if (k <= 3 && parseInt((f % 100) / 10, 10) === 1) {
                k = 0
            }
            return ["st", "nd", "rd"][k - 1] || "th"
        }, w: function () {
            return h.getDay()
        }, z: function () {
            var k = new Date(e.Y(), e.n() - 1, e.j());
            var f = new Date(e.Y(), 0, 1);
            return Math.round((k - f) / 86400000)
        }, W: function () {
            var k = new Date(e.Y(), e.n() - 1, e.j() - e.N() + 3);
            var f = new Date(k.getFullYear(), 0, 4);
            return d(1 + Math.round((k - f) / 86400000 / 7), 2)
        }, F: function () {
            return c[6 + e.n()]
        }, m: function () {
            return d(e.n(), 2)
        }, M: function () {
            return e.F().slice(0, 3)
        }, n: function () {
            return h.getMonth() + 1
        }, t: function () {
            return (new Date(e.Y(), e.n(), 0)).getDate()
        }, L: function () {
            var f = e.Y();
            return f % 4 === 0 & f % 100 !== 0 | f % 400 === 0
        }, o: function () {
            var l = e.n();
            var f = e.W();
            var k = e.Y();
            return k + (l === 12 && f < 9 ? 1 : l === 1 && f > 9 ? -1 : 0)
        }, Y: function () {
            return h.getFullYear()
        }, y: function () {
            return e.Y().toString().slice(-2)
        }, a: function () {
            return h.getHours() > 11 ? "pm" : "am"
        }, A: function () {
            return e.a().toUpperCase()
        }, B: function () {
            var k = h.getUTCHours() * 3600;
            var f = h.getUTCMinutes() * 60;
            var l = h.getUTCSeconds();
            return d(Math.floor((k + f + l + 3600) / 86.4) % 1000, 3)
        }, g: function () {
            return e.G() % 12 || 12
        }, G: function () {
            return h.getHours()
        }, h: function () {
            return d(e.g(), 2)
        }, H: function () {
            return d(e.G(), 2)
        }, i: function () {
            return d(h.getMinutes(), 2)
        }, s: function () {
            return d(h.getSeconds(), 2)
        }, u: function () {
            return d(h.getMilliseconds() * 1000, 6)
        }, e: function () {
            var f = "Not supported (see source code of date() for timezone on how to add support)";
            throw new Error(f)
        }, I: function () {
            var k = new Date(e.Y(), 0);
            var m = Date.UTC(e.Y(), 0);
            var f = new Date(e.Y(), 6);
            var l = Date.UTC(e.Y(), 6);
            return ((k - m) !== (f - l)) ? 1 : 0
        }, O: function () {
            var k = h.getTimezoneOffset();
            var f = Math.abs(k);
            return (k > 0 ? "-" : "+") + d(Math.floor(f / 60) * 100 + f % 60, 4)
        }, P: function () {
            var f = e.O();
            return (f.substr(0, 3) + ":" + f.substr(3, 2))
        }, T: function () {
            return "UTC"
        }, Z: function () {
            return -h.getTimezoneOffset() * 60
        }, c: function () {
            return "Y-m-d\\TH:i:sP".replace(b, a)
        }, r: function () {
            return "D, d M Y H:i:s O".replace(b, a)
        }, U: function () {
            return h / 1000 | 0
        }
    };
    var j = function (k, f) {
        h = (f === undefined ? new Date() : (f instanceof Date) ? new Date(f) : new Date(f * 1000));
        return k.replace(b, a)
    };
    return j(i, g)
};


// 获取枚举值
export function getRemoteEnum(names, completePromise) {
    let complete = $.Deferred(),
        getArr = [];
    if (names instanceof Array) {
        if (completePromise !== undefined) {
            complete = completePromise;
        }
    } else {
        let arr = Array.prototype.slice.call(arguments);
        names = arr;
    }
    names.forEach(function (value) {
        if ("MAIN_BR_NAME" == value) {
            getArr.push($.get("/api/auto/dict/brNames"));
        } else if ("TOP_ORG_CHILD" == value) {
            getArr.push($.get("/api/auto/dict/topOrgChild"));
        } else if ("CHECK_REPORT_FILE_TYPE" == value) {
            getArr.push($.get("/api/auto/dict/checkReportFileType"));
        } else {
            getArr.push($.get("/api/auto/dict/getList", {name: value, size: 100}));
        }
    });
    $.when.apply(this, getArr).done(function () {
        var resArr = [];
        if (names.length === 1) {
            resArr.push(arguments);
        } else {
            resArr = Array.prototype.slice.call(arguments)
        }
        var retObj = {};
        resArr.forEach(function (value) {
            var dataList = value[0].data.list || value[0].data || [];
            dataList.forEach(function (value1) {
                var keyName = value1["name"];
                if (names.indexOf(keyName) > -1) {
                    if (!retObj[keyName]) {
                        retObj[keyName] = [{name: "--请选择--", val: ""}];
                    }
                    retObj[keyName].push({val: value1.vKey, name: value1.vValue});
                }
            });
        });
        if (completePromise === undefined) {
            complete.resolve(retObj);
        } else {
            completePromise.resolve(retObj);
        }
    });
    return completePromise ? completePromise : complete;
}

export function pageGetDataList(that, conf) {
    let data = conf.data;
    if (undefined == data) {
        data = that.listCond;
    }
    let pageSize = conf.pageSize || 5;
    that.loading = true;
    getAjax({
        url: conf.url,
        data: {
            ...data,
            size: pageSize,
            page: that.currentPage
        },
        success: function (res) {
            that.loading = false;
            that.refreshing = false;
            if (res.success) {
                let list = res.data.list;
                if (!list || list.length < pageSize) {
                    that.finished = true;
                } else {
                    that.currentPage++;
                    that.finished = false;
                }
                if (conf.filter) {
                    conf.filter(list);
                }
                that.dataList.push(...list);
            } else {
                that.error = true;
            }
        },
        error: function () {
            that.error = true;
            that.loading = false;
        }
    })
}

export function subDateStr(dateStr) {
    if (dateStr && dateStr.length >= 10) {
        return dateStr.substring(0, 10);
    } else if (dateStr) {
        console.error("请查看字段格式", dateStr);
    }
    return " - ";
};


let callFun = function (formatData, config, formatName) {
    // 传入数组
    if (formatData instanceof Array) {
        var formatDataArr = [];
        formatData.forEach(function (dataItem) {
            formatDataArr.push(callFun(dataItem, config, formatName));
        });
        return formatDataArr;
    }
    // 传入对象
    if (formatData instanceof Object === false) {
        return formatData;
    }
    var format = {};
    for (var key in formatData) {
        if (formatData.hasOwnProperty(key)) {
            // 调用函数格式化key
            var formatKey = formatDataFun[formatName](key, config, true);
            // 若检测value为数组或对象，继续格式化
            if (formatData[key] instanceof Array) {
                format[formatKey] = [];
                for (var i = 0; i < formatData[key].length; i++) {
                    format[formatKey][i] = callFun(formatData[key][i], config, formatName);
                }
            } else if (formatData[key] instanceof Object) {
                format[formatKey] = callFun(formatData[key], config, formatName);
            } else {
                format[formatKey] = formatData[key];
            }
        }
    }
    return format;
};
export const formatData = {
    // 驼峰转下划线格式
    camelToUnderline: function (formatData, config, isCall) {
        if (isCall === true) {
            return formatData.replace(/[A-Z]|\d+/g, function (word, index) {
                var target = word.toLowerCase();
                if (index === 0 && formatData.indexOf(word) === 0) {
                    return target;
                }
                return "_" + target;
            });
        }
        return callFun(formatData, config, "camelToUnderline");
    },
    camelToUnderlineUpper: function (formatData, config, isCall) {
        if (isCall === true) {
            var pattern = /[A-Z]/g;
            if (config && config["ignoreNum"] === false) {
                pattern = /[A-Z]|\d/g;
            }
            var target = formatData.replace(pattern, function (word, index) {
                if (index === 0 && formatData.indexOf(word) === 0) {
                    return word.toUpperCase();
                }
                return "_" + word.toUpperCase();
            });
            return target.toUpperCase();
        }
        return callFun(formatData, config, "camelToUnderlineUpper");
    },
    // 下划线格式转camel格式
    underlineToCamel: function (formatData, config, isCall) {
        if (true === isCall) {
            var temp_key = formatData.toLowerCase();
            return temp_key.replace(/_([a-zA-Z0-9])/g, function (word, word2, index) {
                var target = word2.toUpperCase();
                return target;
            });
        }
        return callFun(formatData, config, "underlineToCamel");
    },
    // 下划线转大驼峰格式
    underlineToBigCamel: function (formatData, config, isCall) {
        if (true === isCall) {
            formatData = this.underlineToCamel(formatData, true);
            return formatData.replace(formatData[0], formatData[0].toUpperCase())
        }
        return callFun(formatData, config, "underlineToBigCamel");
    },
    // camel格式转大camel格式
    camelToBigCamel: function (formatData, config, isCall) {
        if (true === isCall) {
            return formatData.replace(formatData[0], formatData[0].toUpperCase());
        }
        return callFun(formatData, config, "camelToBigCamel");
    },
    // 大驼峰转小驼峰格式
    bigCamelToCamel: function (formatData, config, isCall) {
        if (true === isCall) {
            return formatData.replace(formatData[0], formatData[0].toLowerCase())
        }
        return callFun(formatData, config, "camelToBigCamel");
    },
    // 转小写
    toLowerCase: function (formatData, config, isCall) {
        if (isCall) {
            return formatData.toLowerCase();
        }
        return callFun(formatData, config, "toLowerCase");
    },
    // 转大写
    toUpperCase: function (formatData, config, isCall) {
        if (isCall) {
            return formatData.toUpperCase();
        }
        return callFun(formatData, config, "toUpperCase");
    }
};

/**
 * @Author gotomars
 * @Description 根据列合并单元格
 * merge格式：
 * {
 *     列号：[[开始行行号， 结束行行号]]
 * }
 * @Date 9:23 2020/10/29
 **/
export function mergeTableCellByCol(
    rowIndex,
    columnIndex,
    merge
) {
    let x = rowIndex + 1;
    let y = columnIndex + 1;
    if (merge[y]) {
        for (let item of merge[y]) {
            if (item[0] === x) {
                return [(item[1] - item[0]) + 1, 1]
            }
            if (x > item[0] && x <= item[1]) {
                return {
                    rowspan: 0,
                    colspan: 0
                }
            }
        }
    }
}

export function mergeTableCell(
    rowIndex,
    columnIndex,
    merge
) {
    let mergeRow = merge.row;
    let mergeCol = merge.col;
    if (mergeRow[rowIndex + 1]) {
        return mergeTableCellByRow(rowIndex, columnIndex, mergeRow);
    } else if (mergeCol[columnIndex + 1]) {
        return mergeTableCellByCol(rowIndex, columnIndex, mergeCol);
    }
}

/**
 * @Author gotomars
 * @Description 根据行合并单元格
 * merge格式：
 * {
 *     行号：[[开始列列号， 结束列列号]]
 * }
 * @Date 9:23 2020/10/29
 **/
export function mergeTableCellByRow(
    rowIndex,
    columnIndex,
    merge
) {
    let x = rowIndex + 1;
    let y = columnIndex + 1;
    if (merge[x]) {
        for (let item of merge[x]) {
            if (item[0] === y) {
                return [1, (item[1] - item[0]) + 1]
            }
            if ((y > item[0] && y <= item[1]) || y <= item[2]) {
                return [0, 0]
            }
        }
    }
}

export function downloadTmpl(name) {
    location.href = "/api/tmpl/download?name=" + name
}